//生产消费模型

import java.security.PublicKey;
import java.util.concurrent.ArrayBlockingQueue;

public class ProducerConsumer {
    //缓冲队列
    private final ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<>(10);

    //生产者
    class Producer implements Runnable {
        @Override
        public void run() {
            for(int i=0;i<10;i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    arrayBlockingQueue.put(i);
                    System.out.println("put " + i + " into blockingqueue" );
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    //消费者
    class Consumer implements Runnable {
        @Override
        public void run() {
            for(int i=0;i<10;i++) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    int j = arrayBlockingQueue.take();
                    System.out.println("take " + j + " out of blockingqueue" );
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }

    public Producer getProducer() {
        return new Producer();
    }

    public Consumer getConsumer() {
        return new Consumer();
    }

    public static void main(String[] args) {
        ProducerConsumer producerConsumer = new ProducerConsumer();
        new Thread(producerConsumer.getProducer()).start();
        new Thread(producerConsumer.getConsumer()).start();
    }
}
